<?php
require_once '../../config/database.php';

$db = new Database();

// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 检查管理员权限
function checkAdminPermission($requiredPermission = null) {
    global $auth, $db;
    $user = $auth->getCurrentUser();
    if (!$user) {
        Response::authError('请先登录');
    }
    
    // 检查是否为管理员
    $adminUser = $db->fetchOne("
        SELECT au.*, ar.permissions, ar.role_code 
        FROM admin_users au 
        JOIN admin_roles ar ON au.role_id = ar.id 
        WHERE au.user_id = ? AND au.is_active = 1 AND ar.is_active = 1
    ", [$user['id']]);
    
    if (!$adminUser) {
        Response::error('权限不足');
    }
    
    // 检查具体权限
    if ($requiredPermission) {
        $permissions = json_decode($adminUser['permissions'], true);
        if (!in_array('*', $permissions) && !in_array($requiredPermission, $permissions)) {
            // 检查模块权限（如 user.*）
            $modulePermission = explode('.', $requiredPermission)[0] . '.*';
            if (!in_array($modulePermission, $permissions)) {
                Response::error('权限不足');
            }
        }
    }
    
    return $adminUser;
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        $admin = checkAdminPermission('user.view');
        
        switch ($action) {
            case 'list':
                // 获取用户列表
                $page = (int)($_GET['page'] ?? 1);
                $limit = (int)($_GET['limit'] ?? 20);
                $search = $_GET['search'] ?? '';
                $offset = ($page - 1) * $limit;
                
                $whereClause = '';
                $params = [];
                
                if ($search) {
                    $whereClause = "WHERE u.nickname LIKE ? OR u.phone LIKE ? OR u.openid LIKE ?";
                    $searchTerm = "%{$search}%";
                    $params = [$searchTerm, $searchTerm, $searchTerm];
                }
                
                // 获取用户列表
                $users = $db->fetchAll("
                    SELECT u.*, 
                           au.admin_name, au.admin_phone, au.admin_email,
                           ar.role_name, ar.role_code,
                           (SELECT COUNT(*) FROM reservations WHERE user_id = u.id) as reservation_count,
                           (SELECT COUNT(*) FROM activity_applications WHERE user_id = u.id) as activity_count,
                           (SELECT COUNT(*) FROM volunteer_applications WHERE user_id = u.id) as volunteer_count,
                           (SELECT COUNT(*) FROM team_reservations WHERE user_id = u.id) as team_count
                    FROM users u
                    LEFT JOIN admin_users au ON u.id = au.user_id AND au.is_active = 1
                    LEFT JOIN admin_roles ar ON au.role_id = ar.id AND ar.is_active = 1
                    {$whereClause}
                    ORDER BY u.created_at DESC
                    LIMIT ? OFFSET ?
                ", array_merge($params, [$limit, $offset]));
                
                // 获取总数
                $total = $db->fetchOne("
                    SELECT COUNT(*) as count 
                    FROM users u 
                    {$whereClause}
                ", $params)['count'];
                
                Response::success([
                    'users' => $users,
                    'pagination' => [
                        'current_page' => $page,
                        'per_page' => $limit,
                        'total' => (int)$total,
                        'total_pages' => ceil($total / $limit)
                    ]
                ], '获取成功');
                break;
                
            case 'detail':
                // 获取用户详情
                $userId = (int)($_GET['id'] ?? 0);
                if (!$userId) {
                    Response::error('缺少用户ID');
                }
                
                $user = $db->fetchOne("
                    SELECT u.*, 
                           au.admin_name, au.admin_phone, au.admin_email, au.last_login,
                           ar.role_name, ar.role_code, ar.permissions
                    FROM users u
                    LEFT JOIN admin_users au ON u.id = au.user_id AND au.is_active = 1
                    LEFT JOIN admin_roles ar ON au.role_id = ar.id AND ar.is_active = 1
                    WHERE u.id = ?
                ", [$userId]);
                
                if (!$user) {
                    Response::error('用户不存在');
                }
                
                // 获取用户的预约统计
                $reservationStats = $db->fetchOne("
                    SELECT 
                        COUNT(*) as total_reservations,
                        COUNT(CASE WHEN status = 'confirmed' THEN 1 END) as confirmed_count,
                        COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled_count,
                        COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_count
                    FROM reservations 
                    WHERE user_id = ?
                ", [$userId]);
                
                // 获取用户的活动申请统计
                $activityStats = $db->fetchOne("
                    SELECT 
                        COUNT(*) as total_applications,
                        COUNT(CASE WHEN status = 'approved' THEN 1 END) as approved_count,
                        COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count
                    FROM activity_applications 
                    WHERE user_id = ?
                ", [$userId]);
                
                $user['statistics'] = [
                    'reservations' => $reservationStats,
                    'activities' => $activityStats
                ];
                
                Response::success($user, '获取成功');
                break;
                
            case 'reservations':
                // 获取用户的预约记录
                $userId = (int)($_GET['user_id'] ?? 0);
                if (!$userId) {
                    Response::error('缺少用户ID');
                }
                
                $reservations = $db->fetchAll("
                    SELECT r.*, ts.slot_name, ts.start_time, ts.end_time,
                           (SELECT COUNT(*) FROM reservation_companions WHERE reservation_id = r.id) as companion_count
                    FROM reservations r
                    LEFT JOIN museum_time_slots ts ON r.time_slot_id = ts.id
                    WHERE r.user_id = ?
                    ORDER BY r.visit_date DESC, r.created_at DESC
                ", [$userId]);
                
                Response::success($reservations, '获取成功');
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'POST':
        $admin = checkAdminPermission('user.create');
        
        switch ($action) {
            case 'set_admin':
                // 设置用户为管理员
                if (!isset($input['user_id']) || !isset($input['role_id'])) {
                    Response::error('缺少必要参数');
                }
                
                $userId = (int)$input['user_id'];
                $roleId = (int)$input['role_id'];
                $adminName = $input['admin_name'] ?? '';
                $adminPhone = $input['admin_phone'] ?? '';
                $adminEmail = $input['admin_email'] ?? '';
                
                // 检查用户是否存在
                $user = $db->fetchOne("SELECT * FROM users WHERE id = ?", [$userId]);
                if (!$user) {
                    Response::error('用户不存在');
                }
                
                // 检查角色是否存在
                $role = $db->fetchOne("SELECT * FROM admin_roles WHERE id = ? AND is_active = 1", [$roleId]);
                if (!$role) {
                    Response::error('角色不存在或未启用');
                }
                
                // 检查是否已经是管理员
                $existingAdmin = $db->fetchOne("SELECT * FROM admin_users WHERE user_id = ?", [$userId]);
                
                if ($existingAdmin) {
                    // 更新现有管理员信息
                    $result = $db->update('admin_users', [
                        'role_id' => $roleId,
                        'admin_name' => $adminName,
                        'admin_phone' => $adminPhone,
                        'admin_email' => $adminEmail,
                        'is_active' => 1,
                        'updated_at' => date('Y-m-d H:i:s')
                    ], 'user_id = ?', [$userId]);
                } else {
                    // 创建新管理员
                    $result = $db->insert('admin_users', [
                        'user_id' => $userId,
                        'role_id' => $roleId,
                        'admin_name' => $adminName,
                        'admin_phone' => $adminPhone,
                        'admin_email' => $adminEmail,
                        'is_active' => 1
                    ]);
                }
                
                if ($result) {
                    Response::success(['user_id' => $userId], '设置成功');
                } else {
                    Response::error('设置失败');
                }
                break;
                
            case 'set_verifier':
                // 设置用户为核销员
                if (!isset($input['user_id'])) {
                    Response::error('缺少用户ID参数');
                }
                
                $userId = (int)$input['user_id'];
                $isVerifier = (int)($input['is_verifier'] ?? 1);
                
                // 检查用户是否存在
                $user = $db->fetchOne("SELECT * FROM users WHERE id = ?", [$userId]);
                if (!$user) {
                    Response::error('用户不存在');
                }
                
                // 更新用户核销员状态
                $result = $db->update('users', [
                    'is_verifier' => $isVerifier,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = ?', [$userId]);
                
                if ($result) {
                    Response::success(['user_id' => $userId], $isVerifier ? '设置核销员成功' : '取消核销员成功');
                } else {
                    Response::error('操作失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'PUT':
        $admin = checkAdminPermission('user.update');
        
        switch ($action) {
            case 'update_status':
                // 更新用户状态
                if (!isset($input['user_id']) || !isset($input['is_active'])) {
                    Response::error('缺少必要参数');
                }
                
                $userId = (int)$input['user_id'];
                $isActive = (int)$input['is_active'];
                
                $result = $db->update('users', [
                    'is_active' => $isActive,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = ?', [$userId]);
                
                if ($result) {
                    Response::success(['user_id' => $userId], '更新成功');
                } else {
                    Response::error('更新失败');
                }
                break;
                
            case 'remove_admin':
                // 移除管理员权限
                if (!isset($input['user_id'])) {
                    Response::error('缺少用户ID');
                }
                
                $userId = (int)$input['user_id'];
                
                $result = $db->update('admin_users', [
                    'is_active' => 0,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'user_id = ?', [$userId]);
                
                if ($result) {
                    Response::success(['user_id' => $userId], '移除成功');
                } else {
                    Response::error('移除失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'DELETE':
        $admin = checkAdminPermission('user.delete');
        
        switch ($action) {
            case 'delete':
                // 删除用户（软删除）
                $userId = (int)($_GET['id'] ?? 0);
                if (!$userId) {
                    Response::error('缺少用户ID');
                }
                
                // 检查用户是否有相关数据
                $reservationCount = $db->fetchOne("SELECT COUNT(*) as count FROM reservations WHERE user_id = ?", [$userId])['count'];
                if ($reservationCount > 0) {
                    Response::error('用户有预约记录，无法删除');
                }
                
                $result = $db->update('users', [
                    'is_active' => 0,
                    'deleted_at' => date('Y-m-d H:i:s')
                ], 'id = ?', [$userId]);
                
                if ($result) {
                    Response::success(['user_id' => $userId], '删除成功');
                } else {
                    Response::error('删除失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}
?>